package models

import (
	"awesome-devops/applications/tools"
	"awesome-devops/boot"
	"time"
)

type ServerConfig struct {
	BaseModel
	ID         uint      `json:"id"`
	SshIp      string    `json:"ssh_ip"`
	SshPort    int       `json:"ssh_port"`
	SshUser    string    `json:"ssh_user"`
	ServerName string    `json:"server_name"`
	CreateTime time.Time `json:"create_time"`
	UpdateTime time.Time `json:"update_time"`
	DeleteTime int       `json:"delete_time"`
}

func (baseModel *ServerConfig) TableName() string {
	return "ops_server_config"
}

func (baseModel *ServerConfig) FormatServerName() string {
	return baseModel.SshUser + "@" + baseModel.SshIp
}

func (baseModel *ServerConfig) GetSshDriver(timeOutFun func() (time int, echoWords string, callBack func())) *tools.SshCommand {
	std := &tools.StdWriterWithPid{}
	ssh := tools.SshCommand{
		IpAddress:   baseModel.SshIp,
		Port:        baseModel.SshPort,
		UserName:    baseModel.SshUser,
		Stdout:      std,
		Stderr:      std,
		TimeOutFunc: timeOutFun,
	}
	return &ssh
}

func FindServerByIds(projectIds []int) []ServerConfig {
	if len(projectIds) == 0 {
		return make([]ServerConfig, 0)
	}
	config := ServerConfig{}
	var data []ServerConfig
	boot.GetDbConnection().
		Table(config.TableName()).
		Where("delete_time=0 and id in ?", projectIds).
		Find(&data)
	return data
}

//func (baseModel *ServerConfig) BeforeCreate(tx *gorm.DB) (err error) {
//	baseModel.CreateTime = time.Now()
//	baseModel.UpdateTime = time.Now()
//	return tx.Error
//}

//func (baseModel *ServerConfig) BeforeUpdate(tx *gorm.DB) (err error) {
//	baseModel.UpdateTime = time.Now()
//	return tx.Error
//}
